package cn.iocoder.yudao.module.member.service.siteconfiguration;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.module.member.controller.admin.siteconfig.vo.MemberDeviceConfigVo;
import cn.iocoder.yudao.module.member.controller.admin.siteconfig.vo.SiteConfigurationVo;
import cn.iocoder.yudao.module.member.convert.siteconfiguration.MemberDeviceConfigConvert;
import cn.iocoder.yudao.module.member.convert.siteconfiguration.UserPoolConfigConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.siteconfiguration.MemberDeviceConfigDo;
import cn.iocoder.yudao.module.member.dal.dataobject.siteconfiguration.UserPoolConfigDo;
import cn.iocoder.yudao.module.member.dal.mysql.siteconfiguration.MemberDeviceConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.DEVICE_PRICE_EXISTS;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.DEVICE_PRICE_ONE;

@Service
@Validated
public class MemberDeviceConfigServiceImpl implements MemBerDeviceConfigService{


    @Resource
    private MemberDeviceConfigMapper memberDeviceConfigMapper;



    /**
     * 保存前端站点配置信息
     * @param saveReqVO
     */
    @Override
    public void saveConfig(SiteConfigurationVo saveReqVO) {
        if (CollectionUtil.isEmpty(saveReqVO.getMemberDeviceConfigVos())){
            return;
        }
        List<MemberDeviceConfigDo> memberDeviceConfigDos = MemberDeviceConfigConvert.INSTANCE.convertList((saveReqVO.getMemberDeviceConfigVos()));
        //添加校验，必须存在数量唯一的数据
        MemberDeviceConfigDo memberDeviceConfigDo = memberDeviceConfigDos.stream().filter(t -> t.getDeviceNumber().compareTo(BigDecimal.ONE) == 0).findFirst().orElse(null);
        if (memberDeviceConfigDo==null){
            throw exception(DEVICE_PRICE_ONE);
        }

        memberDeviceConfigDos.forEach(t->t.setId(null));
        memberDeviceConfigMapper.insertBatch(memberDeviceConfigDos );
    }

    @Override
    public List<MemberDeviceConfigVo> getConfig() {
        List<MemberDeviceConfigDo> list = memberDeviceConfigMapper.selectList();
        return MemberDeviceConfigConvert.INSTANCE.convertList2(list);
    }

    @Override
    public void deleteBySiteCode(String code) {
        memberDeviceConfigMapper.deleteBySiteCode(code);
    }
}
